const db = require('../db/index');
require('dotenv').config({ path: '.env' })
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')

// 注册
exports.regUser = (req, res) => {
    let userinfo = req.body;

    const sqlStr = 'select * from user where username=?;'
    db.query(sqlStr, userinfo.username, (err, results) => {
        if (err) {
            return res.cc(err);
        }
 
        if (results.length > 0) {
            return res.cc('用户名被占用，请更换其他用户名！');
        }

   
        const sql = 'insert into user set ?;'
    
        db.query(sql, { username: userinfo.username, password: userinfo.password }, (err, results) => {
   
            if (err) return res.cc(err);
      
            if (results.affectedRows !== 1) return res.cc('注册用户失败，请稍后再试!');


            res.cc('注册成功！', 0);
        })
    })

}



// 登录
exports.login = (req, res) => {
    const userinfo = req.body;
    const sql = `select * from user where username=?;`

    db.query(sql, userinfo.username, (err, results) => {
        if (err) return res.cc(err);

        if (results.length !== 1) return res.cc('该用户不存在！');

        if (userinfo.password != results[0].password) return res.cc('密码错误！');

        const user = { ...results[0], password: '', avatar: '' };
        const expiresIn = process.env.expiresIn
        const jwtSecretKey = process.env.jwtSecretKey
        //对用户的信息进行加密 生成Token字符串
        const tokenStr = jwt.sign(user, jwtSecretKey, { expiresIn: expiresIn });

        res.send({
            status: 0,
            message: '登录成功',
            "token": 'Bearer ' + tokenStr,
            retData: user
        })
    })
}